package com.zxn.project.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zxn.project.pojo.R;
import com.zxn.project.pojo.User;
import com.zxn.project.properties.WeiXinProperties;
import com.zxn.project.service.UserService;
import com.zxn.project.util.HttpClientUtil;
import com.zxn.project.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    WeiXinProperties weiXinProperties;
    @Autowired
    UserService userService;
    @Autowired
    HttpClientUtil httpClientUtil;

    @PostMapping("/login")
    public R Login(@RequestBody User user) {

        System.out.println(user);
        //发送网路请求解析code得到openid
        String url = weiXinProperties.getJscode2sessionUrl() +
                "?appid=" + weiXinProperties.getAppid() +
                "&secret=" + weiXinProperties.getSecret() +
                "&js_code=" + user.getCode() +
                "&grant_type=authorization_code";
        System.out.println(url);

        String result = httpClientUtil.doGet(url);
        JSONObject jsonObject = JSON.parseObject(result);
        String openid=jsonObject.get("openid").toString();

        //查询是否数据库中存在openid
        User resultUser = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getOpenid,openid));

        System.out.println(resultUser);
        if (resultUser==null){//不存在,插入用户信息
            user.setOpenid(openid);
            userService.save(user);
        }else {//存在,更新头像和昵称
            resultUser.setNickName(user.getNickName());
            resultUser.setAvatarUrl(user.getAvatarUrl());
            userService.updateById(resultUser);
        }
        String token=JwtUtil.createJWT(result);
        return R.success(token);
    }


}
